package com.security.tool;

import com.security.utils.utils.R;
import com.security.utils.utils.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName TokenLogoutHandler
 * @Description 退出处理器
 * @Author liuzhihui
 * @Date 17/3/2021 下午 10:32
 * @Version 1.0
 **/
public class TokenLogoutHandler implements LogoutHandler {

    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;

    public TokenLogoutHandler(TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        //1、从header里面获取token
        String token = httpServletRequest.getHeader("token");

        //2、token不为空，移除token，从redis中删除token
        if (!StringUtils.isEmpty(token)){
            //从token中获取用户名
            String username = tokenManager.getUserInfoFromToken(token);
            tokenManager.removeToken(token);
            redisTemplate.delete(username);
        }
        ResponseUtil.out(httpServletResponse, R.ok());
    }
}
